package cn.mulanbay.message.handler;

import cn.mulanbay.business.handler.BaseHandler;
import cn.mulanbay.business.handler.lock.RedisDistributedLock;
import cn.mulanbay.message.persistent.service.UserMessageService;
import cn.mulanbay.persistent.entity.UserMessage;
import cn.mulanbay.persistent.enums.MessageSendStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MessageSendHandler extends BaseHandler {

    private static final Logger logger = LoggerFactory.getLogger(MessageSendHandler.class);

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    RedisDistributedLock redisDistributedLock;

    public MessageSendHandler() {
        super("消息发送");
    }

    /**
     * 发送消息
     *
     * @param message
     * @return
     */
    public boolean sendMessage(UserMessage message) {
        boolean needLock;
        if (message.getId() == null) {
            needLock = false;
        } else {
            needLock = true;
        }
        //这个message有可能在其他地方被设置了id
        String key = "messageSendLock:" + message.getId();
        try {
            if (needLock) {
                boolean b = redisDistributedLock.lock(key, 0);
                if (!b) {
                    logger.warn("消息ID=" + message.getId() + "正在被发送，无法重复发送");
                    return true;
                }
            }
            //todo Step1: 获取微信openId信息
            //todo Step2: 发送微信公众号模板消息
            boolean res = true;
            if(res){
                message.setSendStatus(MessageSendStatus.SEND_SUCCESS);
            }else{
                message.setSendStatus(MessageSendStatus.SEND_FAIL);
            }
            message.setLastSendTime(LocalDateTime.now());
            this.saveMessage(message);
            return res;
        } catch (Exception e) {
            logger.error("发送消息失败，id=" + message.getId(), e);
            return false;
        } finally {
            if (needLock) {
                boolean b = redisDistributedLock.releaseLock(key);
                if (!b) {
                    logger.warn("释放消息发送锁key=" + key + "失败");
                }
            }
        }
    }

    /**
     * 直接扔掉
     *
     * @param message
     */
    private void saveMessage(UserMessage message) {
        try {
            if(message.getId()==null){
                userMessageService.save(message);
            }else{
                userMessageService.updateById(message);
            }
        } catch (Exception e) {
            logger.error("保持用户消息异常", e);
        }
    }

}
